var startT;
var endT;
var opMap = {};
// 游玩日期日历
var localfunCalendar = lv.calendar({
    // autoRender: false,
    trigger: ".JS_localfun_calendar",
    triggerEvent: "click",
    offsetAmount: {
        left: 1,
        top: 0
    },
    template: "big",
    completeCallback: lfCompleteCallback,
    selectDateCallback:function (cal) {
       // 把选中日期的价格赋值给下面的个数input框的属性
       var selectedDatePrice = opMap[cal.$trigger.val()].price;
       $(cal.$trigger).parent().parent().siblings(".orderNumBox").find("input").attr("data-selected-price",selectedDatePrice);
       $(cal.$trigger).parents(".orderCanlender").siblings(".orderPrice").find(".order-price").html('<dfn>￥</dfn>'+selectedDatePrice);

        var ele = cal.$trigger.parents(".orderCanlender").siblings(".orderNumBox").find(".numberText");

        var reFlag = ele.data("sale-re-flag");

        var selectedPrice = ele.attr("data-selected-price");

        if(reFlag=="wifi"){
            fillReSaleOrderInfo(reFlag,"WIFI电话卡",selectedPrice);
        }
        if(reFlag=="otherTicket"){
            fillReSaleOrderInfo(reFlag,"其他票",selectedPrice);
        }
        if(reFlag=="singleTicket"){
            fillReSaleOrderInfo(reFlag,"景点门票",selectedPrice);
        }
        if(reFlag=="connects"){
            fillReSaleOrderInfo(reFlag,"交通接驳",selectedPrice);
        }
        if(reFlag=="showTicket"){
            fillReSaleOrderInfo(reFlag,"演出票",selectedPrice);
        }
       checkStock();
    }
});



// wifi级联日历
var cascadingCalendar = lv.calendar({
    autoRender: false,  //弹出后渲染
    trigger: ".JS_localfun_cascading_calendar",  //目标元素选择器
    triggerEvent: "click",  //触发事件
    offsetAmount: {
        left: 1,
        top: 0
    },
    template: "big",  //使用小日历模板
    cascading: true,  //级联日历
    cascadingOffset: $("#wifiRentDayLimit").data("min")-1,  //结束日期自动跳转天数
    cascadingMin: $("#wifiRentDayLimit").data("min")-1, // 最少预订天数
    cascadingMax:$("#wifiRentDayLimit").data("max")-1,
    cascadingEndNotShowStart: true, //级联第二个日历不显示第一个选中元素
    completeCallback: lfCompleteCallback,
    selectDateCallback:function (cal) {
        var currentInput  = cal.$trigger.attr("data-flag");
        if('startTime' == currentInput){
            startT = cal.$trigger.val();
            if(null != endT){
                var st = lv.calendar.getDateFromFormattedString(startT, "yyyy-MM-dd");
                var et = lv.calendar.getDateFromFormattedString(endT, "yyyy-MM-dd");
                if(et <= st){
                    endT = startT;
                }
            }
        }else if('endTime' == currentInput){
            endT = cal.$trigger.val();
        }

        var selectedDatePrice = 0;
        var lowPrice = 999999;//设置一个大值和小值比较
        // 把选中日期的价格赋值给下面的个数input框的属性 wifi需要获取日期区间的价格总价
        if(null != startT && null != endT){
            var startTime = lv.calendar.getDateFromFormattedString(startT, "yyyy-MM-dd");
            var endTime = lv.calendar.getDateFromFormattedString(endT, "yyyy-MM-dd");

            if(lv.calendar.isSameDay(startTime,endTime)){
                selectedDatePrice = opMap[endT].price;
                lowPrice = selectedDatePrice;
            }else if(endTime > startTime){
                var flag =true;
                var currentDateStr;
                while(flag){
                    currentDateStr = lv.calendar.dateFormat(startTime, "yyyy-MM-dd");
                    selectedDatePrice = selectedDatePrice + opMap[currentDateStr].price;
                    if(lowPrice>opMap[currentDateStr].price)lowPrice = opMap[currentDateStr].price;
                    if(lv.calendar.isSameDay(startTime,endTime))flag = false;
                    startTime = lv.calendar.dateOffset(startTime, 1);
                }
            }
        }
        if(lowPrice==999999)lowPrice = 0;
        $(cal.$trigger).parent().parent().siblings(".orderNumBox").find("input").attr("data-selected-price",selectedDatePrice);
        $(cal.$trigger).parents(".orderCanlender").siblings(".orderPrice").find(".order-price").html('<dfn>￥</dfn>'+lowPrice);
        checkStock();
    }
});


function lfCompleteCallback(cal) {
    // var range = cal.$trigger.data("range");
    // 填充价格
    opMap={};
    cal.loading();
    var options = $(cal.$trigger).parent().parent().next("select").children();
    options.each(function () {
        var timePrice = {};
        var data = $(this).text();
        var price = $(this).val();
        var stock = $(this).attr("data-stock");//库存
        var stockFlag = $(this).attr("data-stockFlag");// 是否限制日库存Y,N
        var oversellFlag = $(this).attr("data-oversellFlag")==null?"N":"Y";//是否超卖

        timePrice.price = price/100;
        timePrice.stock = stock;
        timePrice.stockFlag = stockFlag;
        timePrice.oversellFlag = oversellFlag;
        opMap[data] = timePrice;
    });

    // //日历数据填充
    cal.wrap.find('td').each(function(){
        var $this = $(this);
        $this.children().addClass("caldisabled");
        var $calactive = $this.find('.calactive'); //提示信息
        var $calprice = $this.find('.calprice'); //价格信息
        var dateMap = $this.data('date-map');//日历时间
        if (opMap[dateMap]==undefined){
            $this.children().removeClass("caldate").addClass("nodate");

        }else {
            if('Y' == opMap[dateMap].stockFlag && (opMap[dateMap].stock <= 0 || null == opMap[dateMap].stock) && opMap[dateMap].oversellFlag=="N"){
                $this.find(".calinfo").addClass("sellout");//售罄
                $this.find(".calinfo").html("售罄");
                $this.children().removeClass("caldate").addClass("nodate");
            }else{
                //显示价格
                $calprice.html('<i>&yen;</i><em>' + opMap[dateMap].price + '</em>');
                $this.children().removeClass("caldisabled");
            }
        }
    });

    cal.loaded();
}



$(function () {
    chooseNum({
        even: "blur",//默认
        trigger: ".numberText",//必填
        addEvent: "click",//默认
        addTrigger: ".numberAdd",//选填
        subEvent: "click",//默认
        subTrigger: ".numberSub",//选填
        callback: function (ele) {

            var dataName = ele.attr("data-name");
            ele.attr("name",dataName+".quantity");
            $("input[data-name='"+dataName+".goodsId']").attr("name",dataName+".goodsId");
            $("input[data-name='"+dataName+".mainItem']").attr("name",dataName+".mainItem");
            $("input[data-name='"+dataName+".visitTime']").attr("name",dataName+".visitTime");
            $("input[data-name='"+dataName+".wifiAdditation.backTime']").attr("name",dataName+".wifiAdditation.backTime");
            $("input[data-name='"+dataName+".useSameVisitTimeFlag']").attr("name",dataName+".useSameVisitTimeFlag");

            var reFlag = ele.data("sale-re-flag");


            //交通接驳的服务信息动态加载
            if(reFlag == "connects"){
                var branchId = ele.data("branch");
                var branchCode = ele.data("branch-code");
                var productType = ele.data("product-type");
                var maxPeopleNumber = ele.data("max-people-number");
                var maxLuggageNumber = ele.data("max-luggage-number");
                var remark = ele.data("remark");
                if(branchCode=="rent_car" || branchCode=="access_air"|| branchCode=="give_air"){
                    if($("#connectsAddition #"+branchCode).children().length == 0&&ele.val()>0){
                        $("#connectsAddition #"+branchCode).load("/vst_front/book/ajax/queryConnectsServiceInfo.do",{"branchId":branchId,"branchCode":branchCode,"productType":productType,"maxPeopleNumber":maxPeopleNumber,"maxLuggageNumber":maxLuggageNumber,"remark":remark,"type":"new"});
                    }else if($("#connectsAddition #"+branchCode).children().length  > 0&&ele.val()==0){
                        $("#connectsAddition #"+branchCode).html("");
                    }else if(ele.val()>1){

                        //数量大于1的时候要改变用车人数的最大值
                        var newMaxPeopleNumber = maxPeopleNumber*ele.val();
                        $("#"+branchCode+" .numberText").attr("maxval",newMaxPeopleNumber);
                    }

                }
            }
            //wifi电话卡的取还网点动态加载
            if(reFlag=="wifi"){
                var goodsType=ele.data("goods-type");
                var suppGoodsId = ele.data("supp-goods-id");
                var productType = ele.data("product-type");
                var params = {"goodsType":goodsType,"suppGoodsId":suppGoodsId,"productType":productType,"type":"new"};
                if($("#wifiAddition").children().length == 0&&ele.val()>0){
                    $.ajax({
                        type : "POST",
                        async: false,
                        url : "/vst_front/book/ajax/queryWifiPickingPointInfo.do",
                        dataType : "html",
                        data : params,
                        success : function(result) {
                            $("#wifiAddition").html(result);
                            loadWifiAdditionDivCallBack(ele);
                        }
                    });
                }
                var eleVisitDateInput=null;
                if(productType =="WIFI"){
                	eleVisitDateInput = ele.parents(".orderNumBox").siblings(".orderCanlender").find("input[data-flag='startTime']");
                }else if(productType=="PHONE"){
                	eleVisitDateInput = ele.parents(".orderNumBox").siblings(".lf-orderCanlender-date").find("input");
                }
                if(eleVisitDateInput && eleVisitDateInput!=null){
            		params["startDate"] = eleVisitDateInput.val();
            	}
            	params["goodsQuantity"] = ele.val();
            	$.ajax({
            		url : "/vst_front/book/ajax/queryDepositGood.do",
            		type : "post",
            		async: false,
            		data : params,
            		success : function(data) {
            			if(data.depositGoodId==null)return;
            			$("#depositGoodId").attr("name","itemMap["+data.depositGoodId+"].goodsId");
            			$("#depositQuantity").attr("name","itemMap["+data.depositGoodId+"].quantity");
            			$("#depositVisitime").attr("name","itemMap["+data.depositGoodId+"].visitTime");
            			$("#depositGoodId").attr("value",data.depositGoodId);
            			$("#depositQuantity").attr("value",data.depositQuantity);
            			$("#depositVisitime").attr("value",data.depositVisitTime);
            			$("#depositGoodId").attr("data-price",data.depositAmount);
            			$("#depositGoodId").attr("data-quantity",data.depositQuantity);
            		}
            	});
                if($("#wifiAddition").children().length > 0&&ele.val()==0){
                    $("#wifiAddition").html("");
                }
            }

            //配送信息动态加载
            var goodsType=ele.data("goods-type");
            //需要配送信息的为交通接驳商品的city_traffic，traffic_ticket 和
            //除了交通接驳之外的goodsType=="EXPRESSTYPE_DISPLAY"的商品
            var connectsNeedExpressage = ("connects"==reFlag) && (branchCode=="city_traffic" || branchCode=="traffic_ticket");
            if(("connects"!=reFlag && goodsType=="EXPRESSTYPE_DISPLAY")||connectsNeedExpressage){
                //如果界面上本来就存在expressageInfoDiv就不用重复加载了，界面上存在的配送信息id都是expressageInfoDiv
                if($("#expressageInfoDiv").children().length == 0){
                    if($("#deliveryAddtion").children().length == 0&&ele.val()>0){

                        $.ajax({
                            type : "POST",
                            async: true,
                            url : "/vst_front/book/ajax/queryDeliveryInfo.do",
                            dataType : "html",
                            data : {"type":"new"},
                            success : function(result) {
                                $("#deliveryAddtion").html(result);
                                NewExpress.init(path);

                                $("input[name='expressageCheckbox']").live("click",function(){
                                    var phone = $(this).attr("mobile");
                                    var name = $(this).attr("personname");
                                    var receiverId = $(this).val();
                                    if($(this).prop("checked")){
                                        $(this).closest("label").siblings().find("input").prop("checked",false);
                                        $(".expressage_info").find("input[name *= 'fullName']").val(name);
                                        $(".expressage_info").find("input[name *= 'mobile']").val(phone);
                                        $(".expressage_info").find("input[name *= 'receiverId']").val(receiverId);
                                        $(".expressage_info").find("input[name = 'expressage.recipients']").val(name);
                                        $(".expressage_info").find("input[name = 'expressage.contactNumber']").val(phone);

                                    }else if(!$(this).prop("checked")){
                                        $(".expressage_info").find("input[name *= 'fullName']").val("");
                                        $(".expressage_info").find("input[name *= 'mobile']").val("");
                                        $(".expressage_info").find("input[name *= 'receiverId']").val("");
                                        $(".expressage_info").find("input[name = 'expressage.recipients']").val("");
                                        $(".expressage_info").find("input[name = 'expressage.contactNumber']").val("");
                                    }
                                });
                            }
                        });
                    }
                }
                //当数量input为0时，需要判断是否需要删除动态生成的配送信息
                if($("#deliveryAddtion").children().length > 0&&ele.val()==0){
                    //需要配送信息的关联商品的条数为0的时候才删除
                    var needDeliveryAddtionNum = 0;
                    $("input[data-goods-type='EXPRESSTYPE_DISPLAY']").each(function () {
                        //交通接驳的access_air，give_air，rent_car不需要配送信息
                        var connectNotNeedExpressage = $(this).data("branch-code")!="access_air" && $(this).data("branch-code")!="give_air" && $(this).data("branch-code")!="rent_car";
                        if($(this).val()>0 && connectNotNeedExpressage){
                            needDeliveryAddtionNum = needDeliveryAddtionNum + 1;
                        }
                    });
                    if(needDeliveryAddtionNum==0){
                        $("#deliveryAddtion").html("");
                    }
                }
            }



            var selectedPrice = ele.attr("data-selected-price");

            if(reFlag=="wifi"){
                fillReSaleOrderInfo(reFlag,"WIFI电话卡",selectedPrice);
            }
            if(reFlag=="otherTicket"){
                fillReSaleOrderInfo(reFlag,"其他票",selectedPrice);
            }
            if(reFlag=="singleTicket"){
                fillReSaleOrderInfo(reFlag,"景点门票",selectedPrice);
            }
            if(reFlag=="connects"){
                fillReSaleOrderInfo(reFlag,"交通接驳",selectedPrice);
            }
            if(reFlag=="showTicket"){
                fillReSaleOrderInfo(reFlag,"演出票",selectedPrice);
            }

            checkStock();
        }
    });

});


//wifi addition div加载后的回调
function loadWifiAdditionDivCallBack(ele){
    $(".wfDetailSelect").bind("click",function(event){
        var cityId = $(this).attr("cityId");
        var goodsType=ele.data("goods-type");
        var suppGoodsId = ele.data("supp-goods-id");
        var productType = ele.data("product-type");
        $.ajax({
            type : "POST",
            async: true,
            url : "/vst_front/book/ajax/queryWifiPickingPointInfo.do",
            dataType : "html",
            data : {"goodsType":goodsType,"cityId":cityId,"suppGoodsId":suppGoodsId,"productType":productType,"type":"new"},
            success : function(result) {
                $("#wifiAddition").html(result);
                loadWifiAdditionDivCallBack(ele);
            }
        });
    });

    $("input[name='contactsPersonCheckbox']").live("click",function(){
        var phone = $(this).attr("mobile");
        var name = $(this).attr("personname");
        var receiverId = $(this).val();
        if($(this).prop("checked")){
            $(this).closest("label").siblings().find("input").prop("checked",false);
            $(".user_info").find("input[name *= 'fullName']").val(name);
            $(".user_info").find("input[name *= 'mobile']").val(phone);
            $(".user_info").find("input[name *= 'receiverId']").val(receiverId);
            $(".user_info").find("input[name = 'expressage.recipients']").val(name);
            $(".user_info").find("input[name = 'expressage.contactNumber']").val(phone);

        }else if(!$(this).prop("checked")){
            $(".user_info").find("input[name *= 'fullName']").val("");
            $(".user_info").find("input[name *= 'mobile']").val("");
            $(".user_info").find("input[name *= 'receiverId']").val("");
            $(".user_info").find("input[name = 'expressage.recipients']").val("");
            $(".user_info").find("input[name = 'expressage.contactNumber']").val("");
        }
    });
}

function chooseNum(opts) {
    if(!opts.subEvent ){
        opts.subEvent = "click";
    }
    if(!opts.addEvent ){
        opts.addEvent = "click";
    }
    if(!opts.even){
        opts.addEvent = "blur";
    }
    $(document).on(opts.even, opts.trigger, function () {
            // console.log($(this));
            var minVal = $(this).attr("minVal");
            var maxVal = $(this).attr("maxVal");
            var inputVal = $(this).val();
            var addElement = $(this).siblings('.num_add');
            var subtractionElement = $(this).siblings('.num_subtraction');
            var $tip =$(this).parent(".num_box").next(".tiptext");
            if (minVal - maxVal == 0) {
                $(this).val(minVal);
                $(addElement).addClass("num_stop");
                $(subtractionElement).addClass("num_stop");
                $($tip).css("display","block");
            } else if (inputVal - maxVal > 0) {
                $(this).val(maxVal);
                $(addElement).addClass("num_stop");
                $($tip).css("display","block");
                $(subtractionElement).removeClass("num_stop");
            } else if (inputVal - minVal < 0) {
                $(this).val(0);
                $(subtractionElement).addClass("num_stop");
                $(addElement).removeClass("num_stop");
                $($tip).css("display","none");
            } else {
                $(subtractionElement).removeClass("num_stop");
                $(addElement).removeClass("num_stop");
                $($tip).css("display","none");
            }
            var currentVal = $(this).val();
            // opts.callback(currentVal);
        if (typeof opts.callback == "function") {
            opts.callback($(this));
        }
    });

    if (null != opts.addTrigger && ''!=opts.addTrigger) {
        $(document).on(opts.addEvent, opts.addTrigger, function () {
            var textElement = $(this).siblings(opts.trigger);
            var inputVal = $(textElement).val();
            var minVal = $(textElement).attr("minVal");
            var maxVal = $(textElement).attr("maxVal");
            var $tip =$(this).parent(".num_box").next(".tiptext");
            if(inputVal - 0 ==0){
                if(minVal - 0 > 0){
                    $(textElement).val(minVal);
                    $(this).removeClass("num_stop");
                }else if(minVal - 0 == 0){
                    inputVal++;
                    $(textElement).val(inputVal);
                    $(this).removeClass("num_stop");
                }
            }else if (inputVal - maxVal == 0) {
                $(textElement).val(inputVal);
                $(this).addClass("num_stop");
                $($tip).css("display","block");
            }else{
                inputVal++;
                $(textElement).val(inputVal);
                $(this).removeClass("num_stop");
            }

            $(this).siblings(opts.subTrigger).removeClass("num_stop");
            var currentVal = $(textElement).val();
            if((currentVal - 0 >= 0 )&& (currentVal -maxVal<= 0)){
                // opts.callback(currentVal);
                if (typeof opts.callback == "function") {
                    opts.callback($(textElement));
                }
            }
        });
    }

    if (null != opts.subTrigger && ''!=opts.subTrigger) {
        $(document).on(opts.subEvent, opts.subTrigger, function () {
            var textElement = $(this).siblings(opts.trigger);
            var inputVal = $(textElement).val();
            var minVal = $(textElement).attr("minVal");
            var maxVal = $(textElement).attr("maxVal");
            var $tip =$(this).parent(".num_box").next(".tiptext");
            $($tip).css("display","none");
            if(inputVal-minVal>0){
                inputVal--;
                $(textElement).val(inputVal);
                $(this).removeClass("num_stop");
            }else if(inputVal- minVal == 0){
                $(textElement).val(0);
                $(this).addClass("num_stop")
            }
            $(this).siblings(opts.addTrigger).removeClass("num_stop");
            var currentVal = $(textElement).val();
            if((currentVal - 0 >= 0 )&& (currentVal -maxVal<= 0)){
                if (typeof opts.callback == "function") {
                // opts.callback(currentVal);
                    opts.callback($(textElement));
                }
            }
        });
    }
}



//填充关联销售价格明细
 function fillReSaleOrderInfo(reSaleType,reSaleTypeName,selectedPrice) {
     if(typeof(selectedPrice)== "undefined"){
         return;
     }

     $(".orderTicketInfo-list .js_"+reSaleType).remove();
     var price = 0;
     var resaleTypeHtml = "<ul class=\"js_"+reSaleType+"\">" +
         "<li class=\"primary\"><em>"+reSaleTypeName+"</em><dfn><i>¥</i>" + price + "</dfn></li>";
     $(".ticketLi:visible .js_"+reSaleType).each(function () {
         if ($(this).val() > 0) {
             resaleTypeHtml = resaleTypeHtml+ "<li><em>" + $(this).data("goods-name") + "</em><dfn class=\"dark\"><span class=\"f12\">" + $(this).val() + " X <i>¥</i></span>" + $(this).attr("data-selected-price") + "</dfn></li>";
             price = parseFloat((price + $(this).val() * $(this).attr("data-selected-price")).toFixed(2));
         }
     });
     resaleTypeHtml = resaleTypeHtml+"</ul>";
     //计算填充总价
     if(price>0){
    	 $(".orderTicketInfo-list ul:first").after(resaleTypeHtml);
    	 $(".orderTicketInfo-list .js_"+reSaleType+" .primary dfn").html("<i>¥</i>" + price );
         $(".orderTicketInfo-list .js_"+reSaleType).attr("goodsSaleFlag","Y");
         $(".orderTicketInfo-list .js_"+reSaleType).attr("data-all-price",price);
     }
     $(".orderTicketInfo-list .js_deposit").remove();
     if(reSaleType=="wifi" && $("#depositGoodId") && parseInt($("#depositGoodId").attr("data-price"))>0){
    	 var depositPrice = 0;
    	 var priceToYuan= parseInt($("#depositGoodId").attr("data-price"))/100;
    	 var depositHtml = "<ul class=\"js_deposit\">"+
    	 "<li class=\"primary\"><em>押金</em><dfn><i>¥</i>" + depositPrice + "</dfn></li>";; 
    	 depositHtml += "<li><em>押金</em><dfn class=\"dark\"><span class=\"f12\">" + $("#depositGoodId").attr("data-quantity") + " X <i>¥</i></span>" +  priceToYuan+ "</dfn></li>";
    	 depositPrice = parseInt($("#depositGoodId").attr("data-price"))*parseInt($("#depositGoodId").attr("data-quantity"));
    	 if(!isNaN(depositPrice) && depositPrice>0){
    		 $(".orderTicketInfo-list ul:last").before(depositHtml);
        	 $(".orderTicketInfo-list .js_deposit .primary dfn").html("<i>¥</i>" + (depositPrice/100) );
             $(".orderTicketInfo-list .js_deposit").attr("goodsSaleFlag","Y");
             $(".orderTicketInfo-list .js_deposit").attr("data-all-price",depositPrice/100);
    	 }
    	 
     }
     return price;
}

function bdPickingPoint(){
    $('.wifiOrderDl').each(function(){
        var $this=$(this);
        var len=$this.find('.wifiOrderDd').length;
        if(len<=4)
        {
            $this.find('.wfOrderTake').hide();
        }
        $this.find('.wifiOrderDd:gt(3)').hide();
        $this.find('.wfOrderTake').click(function(){
            var html=$(this).html().split('<');
            var str=html[0].substring(4,6);
            //console.log(html[0].substr(0,4));
            if(html[0].substr(0,4)=='查看全部')
            {
                $this.find('.wifiOrderDd').show();
                $(this).html('收起全部'+str+'地址<i class="arrow arrowUp"></i>');
            }
            else if(html[0].substr(0,4)=='收起全部')
            {
                $this.find('.wifiOrderDd:gt(3)').hide();
                $(this).html('查看全部'+str+'地址<i class="arrow"></i>');
            }
        });
    });
}

